package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.view.LruImageCache;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link NewsDetailFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewsDetailFragment extends Fragment implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private static RequestQueue queue;
    private static ImageLoader imageLoader;

    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    private String getData;  //新闻数据

    private OnFragmentInteractionListener mListener;
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mOption;
    private TextView tv_title_detail;
    private TextView tv_time_detail;
    private TextView tv_look_count_detail;
    private NetworkImageView niv_image_detail;
    private TextView tv_news_content_detail;
    private LinearLayout newsContent;

    public NewsDetailFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewsDetailFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NewsDetailFragment newInstance(String param1, String param2) {
        NewsDetailFragment fragment = new NewsDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            getData = mParam1;
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }
    private void init() {
        manager = getActivity().getSupportFragmentManager();
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue, lruImageCache);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_detail, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {

        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mBack.setOnClickListener(this);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mTitle.setText("新闻详情");
        mOption = (ImageView) view.findViewById(R.id.iv_top_option);
        mOption.setVisibility(View.INVISIBLE);

        tv_title_detail = (TextView) view.findViewById(R.id.tv_title_detail);
        tv_time_detail = (TextView) view.findViewById(R.id.tv_time_detail);
        tv_look_count_detail = (TextView) view.findViewById(R.id.tv_look_count_detail);
        niv_image_detail = (NetworkImageView) view.findViewById(R.id.niv_image_detail);
        newsContent = (LinearLayout) view.findViewById(R.id.ll_news_content);
        niv_image_detail.setOnClickListener(this);
        tv_news_content_detail = (TextView) view.findViewById(R.id.tv_news_content_detail);
//        tv_news_content_detail.setText("正文内容");
        initDat();
    }

    private void initDat() {

        JSONObject o = null;
        try {
            o = new JSONObject(getData);
//            Log.d("数据", "数据"+o.toString());
            String title = o.getString("title");
            tv_title_detail.setText(title);
            String pubDate = o.getString("pubDate");
            String desc = o.getString("desc");
            String source = o.getString("source");
            tv_news_content_detail.setText(source+" "+desc);
            tv_time_detail.setText(pubDate);
            JSONArray imageurls = o.getJSONArray("imageurls");
            String url = "http://news.xinhuanet.com/photo/2011-09/15/122034862_21n.jpg";
            if (imageurls.length()>0) {
                url = imageurls.getJSONObject(0).getString("url");
                niv_image_detail.setImageUrl(url,imageLoader);
            }

            JSONArray array = o.getJSONArray("allList");
//            StringBuffer content = new StringBuffer("   ");
            for (int i = 0; i < array.length(); i++) {
                Object obj = array.get(i);
                if (obj instanceof JSONObject) {
                    JSONObject image = (JSONObject) obj;
                    NetworkImageView imageView = new NetworkImageView(getActivity());
                    imageView.setImageUrl(image.getString("url"),imageLoader);
                    newsContent.addView(imageView);
                } else {
//                    content.append(array.getString(i));
                    TextView textView = new TextView(getActivity());
                    textView.setPadding(20,20,20,20);
                    textView.setText(array.getString(i));
                    newsContent.addView(textView);
                }

            }
//            tv_news_content_detail.setText(content.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        mTransaction = manager.beginTransaction();
        switch (v.getId()) {
            case R.id.iv_top_back:
                NewsDetailFragment fragment = (NewsDetailFragment) manager.findFragmentByTag("NewsDetail");
                if (fragment != null) {
                    mTransaction.detach(fragment);
                    mTransaction.commit();
                }

                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
